class Username < ActiveRecord::Base
  belongs_to :user
  belongs_to :authentication_type

  validates_presence_of :username, :authentication_type_id
  validates_uniqueness_of :username
  validates_presence_of :password, :if => :validate_password?
  validates_confirmation_of :password, "password_confirmation", :if => :validate_password?

  attr_accessor :check_password

  after_validation :encrypt_password

  private
  def validate_password?
    if self.check_password
      return self.new_record? ? false : self.authentication_type.name == "local"
    else
      return false
    end
  end

  def encrypt_password
    if self.check_password
      sha256 = Digest::SHA256.new
      self.password_salt = ActiveSupport::SecureRandom::hex
      self.password = sha256.hexdigest(self.password + self.password_salt)
    end
  end

end
